package main

import (
	"fmt"
	"sync"
	"time"
)

func IsCanceld(iscancel chan struct{}) bool {
	select {
	case <-iscancel:
		return true
	default:
		return false
	}
}

func cancel_1(cancel chan struct{}) {
	cancel <- struct{}{}
}

func cancel_2(cancel chan struct{}) {
	close(cancel)
}

func main2() {
	cancel := make(chan struct{})

	for i := 0; i < 5; i++ {
		go func(i int, cancel chan struct{}) {
			for {
				if IsCanceld(cancel) {
					break
				}
				time.Sleep(time.Millisecond * 5)
			}
			fmt.Println(i, "done")
		}(i, cancel)
	}
	// cancel_1(cancel)
	cancel_2(cancel)
	time.Sleep(time.Second * 1)
}

func dataProducer(ch chan int, wg *sync.WaitGroup) {
	go func() {
		for i := 0; i < 10; i++ {
			ch <- i
		}
		close(ch)
		wg.Done()
	}()
}

func dataReceiver(ch chan int, wg *sync.WaitGroup) {
	go func() {
		for {
			if data, ok := <-ch; ok {
				fmt.Println(data)
			} else {
				break
			}
		}

		wg.Done()
	}()
}

func main() {
	var wg sync.WaitGroup
	ch := make(chan int)
	wg.Add(1)
	dataProducer(ch, &wg)
	wg.Add(1)
	dataReceiver(ch, &wg)
	wg.Add(1)
	dataReceiver(ch, &wg)
	wg.Wait()
	wg.Wait()
}
